﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using Lucene.Net.Documents;
using CommonSearchModule;
using System.Data.SqlClient;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace CreateIndexFile
{
    public class SearchYiWenIndexFile : IndexFileBase
    {
        public SearchYiWenIndexFile()
            : base(ConfigurationManager.AppSettings["YiWen_IndexDocumentsPath"])
        { }

        #region Public Methods

        public override void Create()
        {
            writer.SetMaxBufferedDocs(10);
            Stopwatch watch = new Stopwatch();
            watch.Start();
            StringBuilder sb;
            using (SqlConnection conn = new SqlConnection(connString_YiWen))
            {
                sb = new StringBuilder();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                sb.Append(@"     
 SELECT  c.id AS ID ,
        c.Name AS Name ,
        c.Description AS info ,
        CategoryName = 2 ,
        c.AddDate AS PackageTime ,
        ExtentionField1 = ( SELECT  COUNT(1)
                            FROM    Question_Tag_R
                            WHERE   QuestionID = c.id
                          ) ,
        ExtentionField2 = ISNULL(c.Logo,'http://static.158.cn/images/user.gif')
FROM    dbo.Tag_Info c

 ");
                comm.CommandText = sb.ToString();
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();

                int rowCount = 1;
                try
                {
                    while (reader.Read())
                    {
                        Search_Entity entity = new Search_Entity();
                        entity.ID = reader["id"].ToString();
                        entity.Name = Regex.Replace(reader["Name"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.Info = Regex.Replace(reader["info"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.CategoryName = reader["CategoryName"].ToString();
                        entity.PackageTime = reader["PackageTime"].ToString();
                        entity.ExtentionField1 = reader["ExtentionField1"].ToString();
                        entity.ExtentionField2 = reader["ExtentionField2"].ToString();
                        //添加到索引
                        Document doc = InitDocument(entity);

                        writer.AddDocument(doc);
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("执行次数：" + rowCount++.ToString());
                        Console.WriteLine("执行时间：" + watch.Elapsed.ToString());
                    }
                }
                finally
                {
                    reader.Close();
                }
            }

            using (SqlConnection conn = new SqlConnection(connString_YiWen))
            {
                sb = new StringBuilder();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                sb.Append(@"     
SELECT  a.id AS id ,
        a.Content AS Name ,
        e.AppendContent AS info ,
        CategoryName = 1 ,
        e.AddDate AS PackageTime ,
        ISNULL(e.AnswerCount,0) AS ExtentionField1 ,
        ISNULL(e.FavoritesCount,0) AS ExtentionField2
FROM    dbo.Question_info a
        INNER JOIN dbo.Question_Ext e ON a.id = e.id

  ");
                comm.CommandText = sb.ToString();
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();

                int rowCount = 1;
                try
                {
                    while (reader.Read())
                    {
                        Search_Entity entity = new Search_Entity();
                        entity.ID = reader["id"].ToString();
                        entity.Name = Regex.Replace(reader["Name"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.Info = Regex.Replace(reader["info"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.CategoryName = reader["CategoryName"].ToString();
                        entity.PackageTime = reader["PackageTime"].ToString();
                        entity.ExtentionField1 = reader["ExtentionField1"].ToString();
                        entity.ExtentionField2 = reader["ExtentionField2"].ToString();
                        //添加到索引
                        Document doc = InitDocument(entity);

                        writer.AddDocument(doc);
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("执行次数：" + rowCount++.ToString());
                        Console.WriteLine("执行时间：" + watch.Elapsed.ToString());
                    }
                }
                finally
                {
                    reader.Close();
                }
            }

            using (SqlConnection conn = new SqlConnection(connString_YiWen))
            {
                sb = new StringBuilder();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                sb.Append(@"     
SELECT  a.userid AS id ,
        a.UserName AS NAME ,
        b.Introduction AS info ,
        CategoryName = 3 ,
        a.RegisterTime AS PackageTime ,
        ExtentionField1 = ( SELECT  COUNT(1)
                            FROM    dbo.Question_Info
                            WHERE   UserID = a.userid
                          ) ,
        ExtentionField2 = ISNULL(b.UserImg,'http://static.158.cn/images/user.gif')
FROM    dbo.User_Info a
        INNER JOIN dbo.User_Extension b ON a.UserID = b.UserID

");
                comm.CommandText = sb.ToString();
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();

                int rowCount = 1;
                try
                {
                    while (reader.Read())
                    {
                        Search_Entity entity = new Search_Entity();
                        entity.ID = reader["id"].ToString();
                        entity.Name = Regex.Replace(reader["Name"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.Info = Regex.Replace(reader["info"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.CategoryName = reader["CategoryName"].ToString();
                        entity.PackageTime = reader["PackageTime"].ToString();
                        entity.ExtentionField1 = reader["ExtentionField1"].ToString();
                        entity.ExtentionField2 = reader["ExtentionField2"].ToString();
                        //添加到索引
                        Document doc = InitDocument(entity);

                        writer.AddDocument(doc);
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("执行次数：" + rowCount++.ToString());
                        Console.WriteLine("执行时间：" + watch.Elapsed.ToString());
                    }
                }
                finally
                {
                    reader.Close();
                }
            }



            writer.Optimize();
            writer.Close();

            TimeSpan _RunTime = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan _RunTime2 = new TimeSpan(DateTime.Now.AddDays(-2).Ticks);
            TimeSpan ss = _RunTime.Subtract(_RunTime2);
            Console.WriteLine(ss.Hours);

            SetCreatePath();
        }

        #endregion Public Methods

        #region Private Methods

        /// <summary>
        /// 初始化Document流中的字段field
        /// Field.Index 	Field.Store 	说明
        /// TOKENIZED（分词） 	YES 	被分词索引且存储
        /// TOKENIZED 	        NO 	被分词索引但不存储
        /// NO 	                YES 	这是不克不及被搜刮的，它只是被搜刮内容的从属物。如URL等
        /// UN_TOKENIZED 	    YES/NO 	不被分词，它作为一个整体被搜刮，搜一项目组是搜不出来的
        /// NO 	                NO 	没有这种用法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected override Document InitDocument(Search_Entity entity)
        {
            Document doc = new Document();

            doc.Add(new Field(FieldKeys.ID, entity.ID.ToString(), Field.Store.YES, Field.Index.NO));
            doc.Add(new Field(FieldKeys.Name, entity.Name, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(FieldKeys.Info, entity.Info, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(FieldKeys.CategoryName, entity.CategoryName, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field(FieldKeys.PackageTime, entity.PackageTime, Field.Store.YES, Field.Index.ANALYZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField1))
                doc.Add(new Field(FieldKeys.ExtentionField1, entity.ExtentionField1, Field.Store.YES, Field.Index.NO));
            if (!string.IsNullOrEmpty(entity.ExtentionField2))
                doc.Add(new Field(FieldKeys.ExtentionField2, entity.ExtentionField2, Field.Store.YES, Field.Index.NO));
            if (!string.IsNullOrEmpty(entity.ExtentionField3))
                doc.Add(new Field(FieldKeys.ExtentionField3, entity.ExtentionField3, Field.Store.YES, Field.Index.NO));
            if (!string.IsNullOrEmpty(entity.ExtentionField4))
                doc.Add(new Field(FieldKeys.ExtentionField4, entity.ExtentionField4, Field.Store.YES, Field.Index.NO));
            if (!string.IsNullOrEmpty(entity.ExtentionField5))
                doc.Add(new Field(FieldKeys.ExtentionField5, entity.ExtentionField5, Field.Store.YES, Field.Index.NO));

            doc.Add(new Field(FieldKeys.SearchKey, "key", Field.Store.NO, Field.Index.NO));

            return doc;
        }
        #endregion Private Methods
    }
}
